package com.app.controller.exportExcel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.app.common.SystemConstant;
import com.app.mapper.AmmunitionMapper;
import com.app.model.AmmunitionModel;
import com.app.model.CategoryModel;
import com.app.model.DepartmentModel;
import com.app.model.PlantModel;
import com.app.service.CategoryService;
import com.app.service.DepartmentService;
import com.app.service.PlantService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 后勤：导出
 */
@RestController
@Controller
@RequestMapping("/api/excel")
public class LogisticsController {

    @Autowired
    private PlantService plantService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AmmunitionMapper ammunitionMapper;
    @Autowired
    private CategoryService categoryService;

    /**
     * 技术厂房/阵地导出
     */
    @PostMapping("/exportPlantsExcel")
    public void exportPlantsExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<PlantModel> plantModelList = plantService.getPlantByIds(appIdList);
        for (int i = 0; i < plantModelList.size(); i++) {
//            if (plantModelList.get(i).getDepartmentId() != null) {
//                DepartmentModel departmentModel = departmentService.getDepByDepId(plantModelList.get(i).getDepartmentId());
//                if (departmentModel != null) {
//                    plantModelList.get(i).setDepartmentName(departmentModel.getName());//部门名称
//                }
//            }
            if (plantModelList.get(i).getIsXx() != null && plantModelList.get(i).getIsXx() == 1) {
                plantModelList.get(i).setIsXxText("有");
            } else if (plantModelList.get(i).getIsXx() != null) {
                plantModelList.get(i).setIsXxText("无");
            }
            if (plantModelList.get(i).getIsEngine() != null && plantModelList.get(i).getIsEngine() == 1) {
                plantModelList.get(i).setIsEngineText("有");
            } else if (plantModelList.get(i).getIsEngine() != null) {
                plantModelList.get(i).setIsEngineText("无");
            }
        }
        map.put("list", plantModelList);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.PlantExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "技术阵地/厂房花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹药检测数量统计导出
     *
     * @param json
     * @param response
     * @throws ParseException
     */
    @PostMapping("/exportAmmunitionExcel")
    public void exportAmmunitionExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        QueryWrapper<AmmunitionModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        queryWrapper.orderByAsc("number").orderByDesc("create_time");
        List<AmmunitionModel> ammunitionModels = ammunitionMapper.selectList(queryWrapper);
        for (AmmunitionModel ammunitionModel : ammunitionModels) {
            List<String> workList = JSON.parseObject( ammunitionModel.getWorkTime(), new TypeReference<List<String>>() {
            });
            StringBuilder stringBuilder = new StringBuilder();
            for (String string : workList) {
                stringBuilder.append(string).append("-");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            ammunitionModel.setWorkTime(stringBuilder.toString());
        }
        map.put("list", ammunitionModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.AmmunitionExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "厂房工作记录导出" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
